# -*- coding: utf-8 -*-
# @Time : 2021/8/6 14:53
# @contact: 1325738369@qq.com
# @Author : tiannan
# @FileName: MinioBucketBase.py
# @Software: PyCharm
import datetime
import json
import logging
from el_lib.json_coders import HPJsonDecoder, HPJsonEncoder
from common.minio_config import minioClient
from minio.error import InvalidResponseError, S3Error
from common.minio_object_base import Object


class Bucket:
    def create_bucket(self, bucket_name):
        try:
            if minioClient.bucket_exists(bucket_name=bucket_name):  # bucket_exists：检查桶是否存在
                logging.info("该存储桶已经存在")
                return 'false'
            else:
                minioClient.make_bucket(bucket_name)
                logging.info("存储桶创建成功")
                return 'true'
        except InvalidResponseError as err:
            logging.info('创建桶出错：%s', err)
            return 'err'

    def get_bucket_list(self):
        bucket_list = []
        try:
            buckets = minioClient.list_buckets()
            for bucket in buckets:
                bucket_list.append({'name': bucket.name, 'creation_date': str(bucket.creation_date)})
            return bucket_list, len(bucket_list), 'ok'
        except InvalidResponseError as err:
            return [], 0, err

    def get_remove_bucket(self, bucket_name):
        try:
            minioClient.remove_bucket(bucket_name)
            logging.info("删除存储桶成功")
            return 'true', 'ok'
        except InvalidResponseError as err:
            logging.info("删除存储桶失败")
            return 'err', err
        except S3Error as err:
            logging.info("删除存储桶失败")
            return 'err', err

    def get_bucket_files(self, bucket_name, file_path):
        try:
            objects = minioClient.list_objects(bucket_name, prefix=file_path,
                                               recursive=False)  # prefix用于过滤的对象名称前缀
            object_list = []
            obj_minio = Object()
            for obj in objects:
                bucket_name = obj.bucket_name
                object_name = str(obj.object_name)
                flag, data = obj_minio.load_object(bucket_name, object_name)
                file_path = bucket_name + '/' + object_name
                last_modified = str(obj.last_modified + +datetime.timedelta(hours=8))
                object_list.append({
                    "file_path": file_path,
                    "file_bytes": data,
                    "bucket_name": bucket_name,
                    "object_name": object_name.split('/')[-1],
                    "is_dir": obj.is_dir,
                    "size": obj.size,
                    "etag": obj.etag,
                    "last_modified": last_modified,
                    "content_type": obj.content_type,
                    "metadata": obj.metadata
                })
            if object_list:
                object_list.sort(key=lambda x: x['last_modified'])
                return 'true', object_list
            return 'false', '请求地址下无存储对象！'
        except InvalidResponseError as err:
            return 'err', err

            # # 列出存储桶中未完整上传的对象

    # def get_list_incomplete_uploads(self, bucket_name):
    #     try:
    #         uploads = minioClient.list_incomplete_uploads(bucket_name,
    #                                                       prefix=None,
    #                                                       recursive=True)
    #         for obj in uploads:
    #             print(obj.bucket_name, obj.object_name, obj.upload_id, obj.size)
    #     except InvalidResponseError as err:
    #         print(err)

    def bucket_policy(self, bucket_name):
        try:
            policy = minioClient.get_bucket_policy(bucket_name)
            print(policy)
        except InvalidResponseError as err:
            print(err)

    # # 给指定的存储桶设置存储桶策略
    # def get_set_bucket_policy(self):
    #     try:
    #         minioClient.set_bucket_policy('testfiles', policy.READ_ONLY)
    #     except InvalidResponseError as err:
    #         print(err)

    def bucket_notification(self, bucket_name):
        try:
            # 获取存储桶的通知配置。
            notification = minioClient.get_bucket_notification(bucket_name)
            print(notification)
            # 如果存储桶上没有任何通知：
            if notification == {}:
                pass
        except InvalidResponseError as err:
            print(err)

    def set_bucket_notification(bucket_name, notification):
        pass

    def remove_all_bucket_notifications(bucket_name):
        try:
            minioClient.remove_all_bucket_notifications('mybucket')
        except InvalidResponseError as err:
            print(err)

    def listen_bucket_notification(bucket_name, prefix, suffix, events):
        pass


if __name__ == '__main__':
    bucket = Bucket()
    bucket.create_bucket('test1234')
    # bucket.get_bucket_list()
    bucket.get_remove_bucket('pic')
    bucket.get_bucket_files('pictures')
    # bucket.get_list_incomplete_uploads('pictures')
    # bucket.bucket_policy('pictures')
